﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Data;
using System.Net;
using BLL;
using Model;
using Newtonsoft.Json;
using System.IO;
using System.Text;

public partial class PersonInfo_WXUser : BasePage
{
    promotionBO mbo = new promotionBO();
    PersonInfoBO pbo = new PersonInfoBO();
    WeiXinRequestBO wbo = new WeiXinRequestBO();
    public string openid="";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (GetQeuryString("para") == "GetList")
        {
            BindData();
        }
        else if (GetQeuryString("para") == "delete")
        {
            try
            {
                Response.Clear();
                string id = GetQeuryString("id");
                promotion m = mbo.GetModel(int.Parse(id));
                mbo.Delete(m.ID);
                Response.Write("ok");
            }
            catch (Exception ex)
            {
                Response.Write("Error" + ex.Message);
            }
            finally
            {
                Response.End();
            }

        }
    }

    private void BindData()
    {
        //Response.Clear();       
        
        DataTable dt= GetInfo();
        string re = ToJson.DataTableToJson(dt.Rows.Count.ToString(), "rows", dt);
        Response.Write(re);
        Response.End();
    }

    private DataTable  GetInfo()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        dt.Columns.Add("openid");
        dt.Columns.Add("nickname");
        dt.Columns.Add("Name");
        dt.Columns.Add("Phone");
        dt.Columns.Add("sex");
        dt.Columns.Add("subscribe_time");
        dt.Columns.Add("Status");
        string access_token = Token();
        string url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token;
        string returnmes = PostRequestGet(url);
        //Response.Write(returnmes);
        Data data = JsonConvert.DeserializeObject<Data>(returnmes);
        for (int i = 0; i < data.data.openid.Length; i++)
        {
            string info = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + data.data.openid[i] + "&lang=zh_CN";
            string infomes = PostRequestGet(info);
            Info winfo = JsonConvert.DeserializeObject<Info>(infomes);
            //openid = winfo.openid;

            DataRow row = dt.NewRow();
            row["openid"] = winfo.openid;
            row["nickname"] = winfo.nickname;
            row["sex"] = winfo.sex;
            if (winfo.sex.Equals("1"))
            {
                row["sex"] = "男";
            }
            else
            {
                row["sex"] = "女";
            }
            row["subscribe_time"] = UnixTimeToTime(winfo.subscribe_time);

            DataSet wxset = wbo.GetStatus(winfo.openid);
            if (wxset != null && wxset.Tables[0] != null && wxset.Tables[0].Rows.Count > 0)
            {
                DataRow dr = wxset.Tables[0].Rows[0];
                DateTime time = UnixTimeToTime(dr[3].ToString());
                DateTime now = DateTime.Now;
                double cha = (now.Day - time.Day) * 24 + (now.Hour - time.Hour) + (now.Minute - time.Minute) * 1/60 + (now.Second - time.Second) *1/3600;
                if (cha < 48)
                {
                    row["Status"] = "可对话";
                }
                else
                {
                    row["Status"] = "不可对话";
                }

            }
            else
            {
                row["Status"] = "不可对话";
            }

            DataSet set = pbo.GetNameByFromUserName(winfo.openid);
            if (set != null && set.Tables[0] != null && set.Tables[0].Rows.Count > 0)
            {
                DataRow dr = set.Tables[0].Rows[0];
                string name = dr[1].ToString();
                string phone = dr[3].ToString();
                //colname.ColumnName = set.Tables[0].Columns["Name"].ColumnName.ToString();
                //colphone.ColumnName = set.Tables[0].Columns["Phone"].ColumnName.ToString();
                //dt.Columns.Add(colname.ColumnName);
                //dt.Columns.Add(colphone.ColumnName); 

                row["Name"] = name;
                row["Phone"] = phone;

            }
            else
            {
                row["Name"] = "该用户未注册或绑定";
                row["Phone"] = "";
            }
            dt.Rows.Add(row);

        }

        dt.DefaultView.Sort = "subscribe_time desc";
        DataTable dtTemp = dt.DefaultView.ToTable();
        ds.Tables.Add(dtTemp);

        return dtTemp;
    }

    private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }



    protected void btnSearch_Click(object sender, EventArgs e)
    {
        BindData();
    }



    class Data
    {
        public string total;
        public string count;
        public Model data;
        public string next_openid;

    }

    class Model
    {
        //public List<string> openid;
        public string[] openid;
    }


    class Info
    {
        public int subscribe;
        public string openid;
        public string nickname;
        public string sex;
        public string language;
        public string city;
        public string province;
        public string country;
        public string headimgurl;
        public string subscribe_time;

    }

    /// <summary>
    /// unix时间转换为datetime
    /// </summary>
    /// <param name="timeStamp"></param>
    /// <returns></returns>
    private DateTime UnixTimeToTime(string timeStamp)
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeStamp + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        return dtStart.Add(toNow);
    }


    // class Product {
    //    public string Name;
    //    public DateTime Expiry;
    //    public Mod  Sizes;

    //}
    //    class Mod
    //    {
    //        public string openid;
    //        public List<string> hehe;
    //    }

    //发送GET请求
    public string PostRequestGet(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "GET";  //定义请求对象，并设置好请求URL地址      
        //request.ProtocolVersion = HttpVersion.Version10;
        //request.ContentType = "image/jpg";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();    //定义响应对象，request在调用GetResponse方法事执行请求了，而不是在HttpWebRequest.Create的时候执行。
        //response.ContentType = "image/jpg";
        Stream stream = response.GetResponseStream(); //定义一个流对象，来获取响应流
        StreamReader sr = new StreamReader(stream, Encoding.UTF8);  //定义一个流读取对象，读取响应流
        string responseHTML = sr.ReadToEnd();
        return responseHTML;
    }
}